import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import os

import spider.tv.tencent
import spider.tv.aiqiyi

import spider.movie.tencent
import spider.movie.aiqiyi

import spider.variety.tencent
import spider.variety.aiqiyi

from tornado.options import options
from tornado.web import RequestHandler, StaticFileHandler

tornado.options.define("port", type=int, default=8000, help="服务器端口")


class IndexHandler(RequestHandler):

    # 主页处理类
    def get(self):
        self.render("index.html")

    def post(self):
        self.render("index.html")


class TvpalyHandler(RequestHandler):
    def post(self):
        name = self.get_argument("name")
        type = self.get_argument("type")
        if type == '1':
            resultTencent = spider.tv.tencent.tencents(self, name)
            resultAiqiyi = spider.tv.aiqiyi.aiqiyi(self, name)
            data = {
                "tencent": resultTencent,
                "aiqiyi": resultAiqiyi,
            }
            self.write(data)
        elif type == '2':
            resultTencent = spider.movie.tencent.tencents(self, name)
            resultAiqiyi = spider.movie.aiqiyi.aiqiyi(self, name)
            data = {
                "tencent": resultTencent,
                "aiqiyi": resultAiqiyi,
            }
            self.write(data)
        elif type == '3':
            resultTencent = spider.variety.tencent.tencents(self, name)
            resultAiqiyi = spider.variety.aiqiyi.aiqiyi(self, name)
            data = {
                "tencent": resultTencent,
                "aiqiyi": resultAiqiyi,
            }
            self.write(data)


if __name__ == '__main__':
    tornado.options.parse_command_line()
    current_path = os.path.dirname(__file__)
    app = tornado.web.Application(
        [

            (r'/', IndexHandler),
            (r'/api/tvplay', TvpalyHandler),
            (r'/(.*)', StaticFileHandler, {
                "path": os.path.join(current_path, "statics/html"),
                "default_filename": "index.html"
            }),
        ],
        static_path=os.path.join(current_path, "static"),
        template_path=os.path.join(current_path, "template"),
        debug=True,
        autoescape=None
    )

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()
